//
//  GestureViewController.m
//  YTwallet
//
//  Created by ZhangLin on 2019/3/14.
//  Copyright © 2019年 hadrlog. All rights reserved.
//

#import "GestureViewController.h"

#import "PCCircleView.h"
#import "PCCircleViewConst.h"
#import "PCLockLabel.h"
#import "PCCircleInfoView.h"
#import "PCCircle.h"
#import <Masonry.h>
#import <LocalAuthentication/LocalAuthentication.h>
#import "ETCommon.h"
#import "AppDelegate.h"
#import "TabBarController.h"
#import "NavigateViewController.h"
#import "LoginViewController.h"



@interface GestureViewController ()<UINavigationControllerDelegate, CircleViewDelegate>

/**
 *  提示Label
 */
@property (nonatomic, strong) PCLockLabel *msgLabel;

/**
 *  解锁界面
 */
@property (nonatomic, strong) PCCircleView *lockView;

/**
 *  infoView
 */
@property (nonatomic, strong) PCCircleInfoView *infoView;


/**
 提示"至少连接四个圆"
 */
@property(nonatomic,strong)UIView *bottomView;




@end

@implementation GestureViewController

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    // 进来先清空存的第一个密码
    [PCCircleViewConst saveGesture:nil Key:gestureOneSaveKey];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"设置手势密码";
    self.view.backgroundColor = [UIColor whiteColor];
    
    if (self.type == GestureViewControllerFromResetVC) {
        NSMutableArray *array = [self.navigationController.viewControllers mutableCopy];
        //把不需要的页面删除
        NSArray *arrayB = @[@"3",@"4"];
        for (int j = 0; j < arrayB.count; j++) {
            NSString *a = [arrayB objectAtIndex:j];
            int b = [a intValue] - j;
            [array removeObjectAtIndex:b];
        }
        //把删除后的控制器数组再次复制
        [self.navigationController setViewControllers:[array copy]];
    }
    
    if (self.type == GestureViewControllerTypeChange) {
        NSMutableArray *array = [self.navigationController.viewControllers mutableCopy];
        //把不需要的页面删除
        NSArray *arrayB = @[@"3"];
        for (int j = 0; j < arrayB.count; j++) {
            NSString *a = [arrayB objectAtIndex:j];
            int b = [a intValue] - j;
            [array removeObjectAtIndex:b];
        }
        //把删除后的控制器数组再次复制
        [self.navigationController setViewControllers:[array copy]];
    }
    
    
    
    
    if (self.type == GestureViewControllerTypeSetting ||
        self.type == GestureViewControllerTypeChange  ||
        self.type == GestureViewControllerFromResetVC) { //设置手势
        //设置手势密码
        [self setupSubViewsSettingVc];
        //设置公共页面
        [self setupSameUI];
        //设置底部视图
        [self createBottomView];
    }else if(self.type == GestureViewControllerTypeLogin)   //登录验证
    {
        
        //登录验证
        [self loginCheck];
        //设置公共页面
        [self setupSameUI];
        
        [self.lockView setType:CircleViewTypeLogin];
        // 头像
        UIImageView  *imageView = [[UIImageView alloc] init];
        [imageView setImage:[UIImage imageNamed:@"password_head"]];
        [self.view addSubview:imageView];
        [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view);
            make.width.mas_equalTo(70);
            make.height.mas_equalTo(70);
            make.bottom.equalTo(self.msgLabel.mas_top).offset(-30);
        }];
        
        UIButton *forgetgesterBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        [forgetgesterBtn setTitleColor:[UIColor colorWithRed:91 / 255.0 green:113 / 255.0 blue:255 / 255.0 alpha:1] forState:(UIControlStateNormal)];
        [forgetgesterBtn setTitle:@"忘记手势密码" forState:(UIControlStateNormal)];
        forgetgesterBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [self.view addSubview:forgetgesterBtn];
        [forgetgesterBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view);
            if (ETScreenH == 568) {
                make.bottom.mas_equalTo(-20);
            }else
            {
                make.bottom.mas_equalTo(-50);
            }
            
        }];
        
        [forgetgesterBtn addTarget:self action:@selector(forgetgesterBtnAction) forControlEvents:(UIControlEventTouchUpInside)];
        
        
        //同时弹出指纹
        if ([AppTools isOpenedFingerprint]) {
            [self TouchId];
        }
    }
}

-(void)forgetgesterBtnAction
{
    NSLog(@"点击了忘记手势密码");
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:@"忘记手势，可以使用账号密码登录，登录后需重新绘制手势图案" preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"密码登录" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"去密码登录");
        LoginViewController *loginVC = [[LoginViewController alloc] init];
        loginVC.type = LoginVCFromGesterVerifyVC;
        
        [AppTools setGesterWrongTimes:0];
        [PCCircleViewConst saveGesture:nil Key:gestureFinalSaveKey];
        
        NavigateViewController *nav = [[NavigateViewController alloc] initWithRootViewController:loginVC];
        [self presentViewController:nav animated:YES completion:nil];
        
    }];
    [alertVC addAction:okAction];
    [alertVC addAction:cancleAction];
    [self presentViewController:alertVC animated:YES completion:nil];
}

-(void)createBottomView
{
    self.bottomView = [[UIView alloc] init];
    [self.view addSubview:self.bottomView];
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(50);
        make.right.mas_equalTo(-50);
        make.top.equalTo(self.view.mas_bottom).offset(-70);
        make.height.mas_equalTo(44);
    }];
    
    UILabel *tipsLab = [[UILabel alloc] init];
    tipsLab.text = @"至少连接四个圆";
    tipsLab.textColor = [UIColor colorWithRed:102 / 255.0 green:102 / 255.0 blue:102 / 255.0 alpha:1];
    tipsLab.font = [UIFont systemFontOfSize:14];
    [self.bottomView addSubview:tipsLab];
    [tipsLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.bottomView).offset(5);
        make.centerY.equalTo(self.bottomView);
    }];
    
    
    UIImageView *imv = [[UIImageView alloc] init];
    imv.image = [UIImage imageNamed:@"icon_explain"];
    [self.bottomView addSubview:imv];
    [imv mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(tipsLab.mas_left).offset(-3);
        make.centerY.equalTo(self.bottomView);
        make.width.mas_equalTo(16);
        make.height.mas_equalTo(16);
    }];
    
}

- (void)setupSameUI
{

    PCLockLabel *msgLabel = [[PCLockLabel alloc] init];
    self.msgLabel = msgLabel;
    self.msgLabel.text = @"请绘制手势密码图案";
    [self.view addSubview:self.msgLabel];
    [self.msgLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(150);
        make.centerX.equalTo(self.view);
        make.width.mas_equalTo(kScreenW);
        make.height.mas_equalTo(14);
    }];
    
    // 解锁界面
    PCCircleView *lockView = [[PCCircleView alloc] init];
    lockView.delegate = self;
    self.lockView = lockView;
    [self.view addSubview:lockView];
    [self.lockView mas_makeConstraints:^(MASConstraintMaker *make) {
         make.top.equalTo(self.msgLabel.mas_bottom).offset(30);
         make.left.mas_equalTo(40);
         make.width.mas_equalTo(self.view.frame.size.width - 80);
         make.height.equalTo(self.lockView.mas_width);
    }];
    
}
//设置手势密码
-(void)setupSubViewsSettingVc
{
    [self.lockView setType:CircleViewTypeSetting];
    
    self.title = @"设置手势密码";
    
    [self.msgLabel showNormalMsg:gestureTextBeforeSet];
    
    PCCircleInfoView *infoView = [[PCCircleInfoView alloc] init];
    self.infoView = infoView;
    [self.view addSubview:self.infoView];
    [self.infoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(60 + 64);
        make.centerX.equalTo(self.view);
        make.width.mas_equalTo(CircleRadius * 2 * 0.6);
        make.height.mas_equalTo(CircleRadius * 2 * 0.6);
    }];
}
//登录验证Check
-(void)loginCheck
{
    [self.lockView setType:CircleViewTypeLogin];
    
    self.title = @"解锁";
    [self.msgLabel showNormalMsg:gestureTextBeforeSet];
}


#pragma mark - circleView - delegate
#pragma mark - circleView - delegate - setting
- (void)circleView:(PCCircleView *)view type:(CircleViewType)type connectCirclesLessThanNeedWithGesture:(NSString *)gesture
{
    NSString *gestureOne = [PCCircleViewConst getGestureWithKey:gestureOneSaveKey];
    
    // 看是否存在第一个密码
    if ([gestureOne length]) {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"重设" style:UIBarButtonItemStylePlain target:self action:@selector(didClickRightItem)];
        [self.msgLabel showWarnMsgAndShake:gestureTextDrawAgainError];
    } else {
        NSLog(@"密码长度不合法%@", gesture);
        [self.msgLabel showWarnMsgAndShake:gestureTextConnectLess];
    }
}

- (void)circleView:(PCCircleView *)view type:(CircleViewType)type didCompleteSetFirstGesture:(NSString *)gesture
{
    NSLog(@"获得第一个手势密码%@", gesture);
    [self.msgLabel showNormalMsg:gestureTextDrawAgain];
    
    // infoView展示对应选中的圆
    [self infoViewSelectedSubviewsSameAsCircleView:view];
}

- (void)circleView:(PCCircleView *)view type:(CircleViewType)type didCompleteSetSecondGesture:(NSString *)gesture result:(BOOL)equal
{
    NSLog(@"获得第二个手势密码%@",gesture);
    
    if (equal) {
        
        NSLog(@"两次手势匹配！可以进行本地化保存了");
        
        [self.msgLabel showNormalMsg:gestureTextSetSuccess];
        [PCCircleViewConst saveGesture:gesture Key:gestureFinalSaveKey];
        [self showSuccessResultTips:@"设置成功" animated:YES forSeconds:SUCCESS_SHOW_TIME_DEF completionBlock:^{
                [self.navigationController popViewControllerAnimated:YES];
        }];
        
        
    } else {
        NSLog(@"两次手势不匹配！");
        
        [self.msgLabel showWarnMsgAndShake:gestureTextDrawAgainError];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"重设" style:UIBarButtonItemStylePlain target:self action:@selector(didClickRightItem)];
    }
}
- (void)didClickRightItem {
    NSLog(@"点击了重设按钮");
    // 1.隐藏按钮
    self.navigationItem.rightBarButtonItem.title = nil;
    
    // 2.infoView取消选中
    [self infoViewDeselectedSubviews];
    
    // 3.msgLabel提示文字复位
    [self.msgLabel showNormalMsg:gestureTextBeforeSet];
    
    // 4.清除之前存储的密码
    [PCCircleViewConst saveGesture:nil Key:gestureOneSaveKey];
}

-(void)fingerPrintLogin
{
    NSString *url = [[ServerAddressModel shareInstance] fullTAnd0AddrWithParameter:@"/epay_apps/login/fingerPrint"];
    [[ETONEHttpClient sharedInstance] doHTTPSPOST:url Parameters:nil HttpBody:nil SuccessHandler:^(id responseObject) {
        
        NSDictionary *dic = [responseObject mj_JSONObject];
        NSString *code = dic[@"code"];
        if ([@"0000" isEqualToString:code]) {
        [self loginSuccessWithResponse:responseObject];
        }
        
    } FailedHandler:^(NSError *error) {
        
    }];
}

//登录成功跳转
-(void)loginSuccessWithResponse:(id )responseObject
{
    
    NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
    NSLog(@"%@",str);
    
    //解析数据
    NSDictionary *dic = [responseObject mj_JSONObject];
    LoginResponse *loginResponse = [LoginResponse mj_objectWithKeyValues:dic];
    [AppTools shareInstance].userInfo = loginResponse.response.userInfo;
    [AppTools shareInstance].msgInfo = loginResponse.response.msgInfo;
    
    /*
    //把登录返回的数据模型存储到本地
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:loginResponse.response.userInfo];
    [[NSUserDefaults standardUserDefaults] setObject:data forKey:@"u"];
     */
    
    //登录成功   更新在本地保存的token
    [AppTools setToken:loginResponse.response.auth_token];
    
    //记录登录状态
    [AppTools saveLoginStatus:YES];
    
    
    TabBarController *tabVC = [[TabBarController alloc] init];
    [UIApplication sharedApplication].keyWindow.rootViewController = tabVC;
    
}

#pragma mark - circleView - delegate - login or verify gesture
- (void)circleView:(PCCircleView *)view type:(CircleViewType)type didCompleteLoginGesture:(NSString *)gesture result:(BOOL)equal
{
    // 此时的type有两种情况 Login or verify
    if (type == CircleViewTypeLogin) {
        
        if (equal) {
            NSLog(@"登陆成功！");
            //验证正确清空错误次数
            [AppTools setGesterWrongTimes:0];
            //手势验证成功登录
            [self fingerPrintLogin];
            
        } else {
            NSLog(@"密码错误！");
            //先取值
            if ([AppTools getGesterWrongTimes] == 0) {
                
                static NSInteger i = 0 ;
                i++;
                [AppTools setGesterWrongTimes:i];
            }else
            {
                NSInteger index = [AppTools getGesterWrongTimes] + 1;
                [AppTools setGesterWrongTimes:index];
                if ([AppTools getGesterWrongTimes] == 5) {
                    NSLog(@"错误了5次了");
                    [AppTools setGesterWrongTimes:0];
                    [PCCircleViewConst saveGesture:nil Key:gestureFinalSaveKey];
                    
                    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"手势密码已失效" message:@"您已连续输错5次手势密码,\n请密码登录" preferredStyle:(UIAlertControllerStyleAlert)];
                    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"密码登录" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                        LoginViewController *loginVC = [[LoginViewController alloc] init];
                        loginVC.type = LoginVCFromGesterVerifyVC;
                        NavigateViewController *nav = [[NavigateViewController alloc] initWithRootViewController:loginVC];
                        [self presentViewController:nav animated:YES completion:nil];
                    }];
                    [alertVC addAction:okAction];
                    [self presentViewController:alertVC animated:YES completion:nil];
                    
                    
                }
            }
            NSInteger times = 5 - [AppTools getGesterWrongTimes];
            [self.msgLabel showWarnMsgAndShake:[NSString stringWithFormat:@"手势密码错误,还可以在输入%ld次",(long)times]];
        }
    } else if (type == CircleViewTypeVerify) {
        
        if (equal) {
            NSLog(@"验证成功，跳转到设置手势界面");
            
        } else {
            NSLog(@"原手势密码输入错误！");
            
        }
    }
}

#pragma mark - infoView展示方法
#pragma mark - 让infoView对应按钮选中
- (void)infoViewSelectedSubviewsSameAsCircleView:(PCCircleView *)circleView {
    for (PCCircle *circle in circleView.subviews) {
        
        if (circle.state == CircleStateSelected || circle.state == CircleStateLastOneSelected) {
            
            for (PCCircle *infoCircle in self.infoView.subviews) {
                if (infoCircle.tag == circle.tag) {
                    [infoCircle setState:CircleStateSelected];
                }
            }
        }
    }
}

#pragma mark - 让infoView对应按钮取消选中

- (void)infoViewDeselectedSubviews {
    [self.infoView.subviews enumerateObjectsUsingBlock:^(PCCircle *obj, NSUInteger idx, BOOL *stop) {
        [obj setState:CircleStateNormal];
    }];
}






-(void)TouchId
{
    NSString *version = [UIDevice currentDevice].systemVersion;
    if ([version integerValue] < 8.0) {
        NSLog(@"系统版本不支持TouchID");
        return;
    }
    LAContext *context = [[LAContext alloc] init];
    context.localizedFallbackTitle = @"";
    NSError *error = nil;
    
    if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
        [context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:@"通过Home键验证已有手机指纹" reply:^(BOOL success, NSError * _Nullable error) {
            
            if (success) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSLog(@"TouchID 验证成功");
                        //指纹验证成功发送登录网络请求
                        [self fingerPrintLogin];
                   
                });
            }else if(error){
                /*
                dispatch_async(dispatch_get_main_queue(), ^{
                        [self showSuccessResultTips:@"验证失败" animated:YES forSeconds:FAIL_SHOW_TIME_DEF];
                });
                 */
                
                switch (error.code) {
                    case LAErrorAuthenticationFailed:{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            NSLog(@"TouchID 验证失败");
                            //当第三次的时候系统会提示验证失败
                            [self showFailedResultTips:@"验证失败" animated:YES forSeconds:1.5];
                        });
                        break;
                    }
                    case LAErrorUserCancel:{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            NSLog(@"TouchID 被用户手动取消");
                        });
                    }
                        break;
                    case LAErrorUserFallback:{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            NSLog(@"用户不使用TouchID,选择手动输入密码");
                        });
                    }
                        break;
                    case LAErrorSystemCancel:{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            NSLog(@"TouchID 被系统取消 (如遇到来电,锁屏,按了Home键等)");
                        });
                    }
                        break;
                    case LAErrorPasscodeNotSet:{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            NSLog(@"TouchID 无法启动,因为用户没有设置密码");
                        });
                    }
                        break;
                    case LAErrorTouchIDNotEnrolled:{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            NSLog(@"TouchID 无法启动,因为用户没有设置TouchID");
                        });
                    }
                        break;
                    case LAErrorTouchIDNotAvailable:{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            NSLog(@"TouchID 无效");
                        });
                    }
                        break;
                    case LAErrorTouchIDLockout:{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [self openSystemPassword];
                            NSLog(@"TouchID 被锁定(连续多次验证TouchID失败,系统需要用户手动输入密码)");
                        });
                    }
                        break;
                    case LAErrorAppCancel:{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            NSLog(@"当前软件被挂起并取消了授权 (如App进入了后台等)");
                        });
                    }
                        break;
                    case LAErrorInvalidContext:{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            NSLog(@"当前软件被挂起并取消了授权 (LAContext对象无效)");
                        });
                    }
                        break;
                    default:
                        break;
                }
            }
        }];
        
    }else{
        NSLog(@"当前设备不支持TouchID");
        //打开系统密码
        [self openSystemPassword];
    }
}

-(void)openSystemPassword
{
    dispatch_async(dispatch_get_main_queue(), ^{
        
        LAContext *myContext=[[LAContext alloc] init];
        NSError *error=nil;
        
        if([myContext canEvaluatePolicy:LAPolicyDeviceOwnerAuthentication error:&error])
        {
            [myContext evaluatePolicy:LAPolicyDeviceOwnerAuthentication localizedReason:@"通过Home键验证已有手机指纹" reply:^(BOOL success, NSError * _Nullable error) {
                
            }];
            
        }
    });
}




@end
